package AddonsSheepContoller.ASPlayer;

import AddonsSheepContoller.Utils.EncryptionAlgorithm;
import AddonsSheepContoller.Utils.SQLiteManager;
import org.bukkit.plugin.Plugin;

import java.sql.ResultSet;
import java.sql.SQLException;

public class ASAccount {
    private int playerPermission;
    private String playerPassword;
    private String playerUsername;
    private String playerUid;
    private String playerEmail;
    public Plugin resourcePlugin;
    public String databaseResourceAddress;
    public boolean isEffective = false;

    public ASAccount(String accountUsername, String accountPassword,
                     Plugin resourcePlugin, String databaseAddress) throws SQLException {
        this.resourcePlugin = resourcePlugin;
        this.databaseResourceAddress = resourcePlugin.getDataFolder()+"/"+databaseAddress;
        loginRequest(accountUsername, accountPassword, resourcePlugin, databaseAddress);
    }

    private void loginRequest(String accountUsername, String accountPassword,
                              Plugin resourcePlugin, String databaseAddress) throws SQLException {
        SQLiteManager loadingDatabase = new SQLiteManager(this.resourcePlugin);
        loadingDatabase.connectDatabase(this.databaseResourceAddress);
        ResultSet resultSet = loadingDatabase.selectData("BasicData",
                new String[]{"username", "password", "permission", "email", "uid"});
        while(true) {
            if(!resultSet.next()) break;

            String getUsername = resultSet.getString("username");
            String getPassword = resultSet.getString("password");
            int getPermission = resultSet.getInt("permission");
            String getEmail = resultSet.getString("email");
            String getUid = resultSet.getString("uid");
            if(getUsername.equalsIgnoreCase(accountUsername))
                if(getPassword.equalsIgnoreCase(EncryptionAlgorithm.sha1(accountPassword))) {
                    this.playerPermission = getPermission;
                    this.playerPassword = getPassword;
                    this.playerUsername = getUsername;
                    this.playerUid = getUid;
                    this.playerEmail = getEmail;
                    this.isEffective = true;
                }
        }

        loadingDatabase.close();
    }

    private void logoutRequest()
    {
        this.playerPermission = 0;
        this.playerPassword = null;
        this.playerUsername = null;
        this.playerUid = null;
        this.playerEmail = null;
        this.isEffective = false;
    }

    public int getPlayerPermission() { return playerPermission; }
    public String getPlayerPassword() { return playerPassword; }
    public String getPlayerUsername() { return playerUsername; }
    public String getPlayerUid() { return playerUid; }
    public String getPlayerEmail() { return playerEmail; }
}
